package com.ad.pet.common.data.loader;

import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;

import com.ad.pet.common.data.local.ContactsUtil;
import com.ad.pet.models.remote.MailList;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import static com.ad.pet.common.data.local.ContactsUtil.PHONES_PROJECTION;


/**
 * Created by z on.
 * Des:通讯录异步loader
 * Date: 2017/3/10
 */

public class ContactsLoader implements LoaderManager.LoaderCallbacks<Cursor> {

    private Context mContext;
    private LoaderCallback<List<MailList>> mCallback;
    private ContactsUtil mContactsUtil;

    @Inject
    public ContactsLoader(Context context, ContactsUtil contactsUtil) {
        mContext = context;
        this.mContactsUtil = contactsUtil;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        CursorLoader loader = new CursorLoader(mContext, ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                , PHONES_PROJECTION, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        List<MailList> mailLists = new ArrayList<>();
        try {
            mContactsUtil.readCursor(mailLists, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //回调通知
        if (mCallback != null) {
            mCallback.complete(mailLists);
        }

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    public void setCallback(LoaderCallback<List<MailList>> callback) {
        if (callback != null) {
            mCallback = callback;
        }
    }


}
